package com.banshuibao.bsb_android.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AuthorizedResultModel;
import com.banshuibao.bsb_android.model.ExpertAnswerDetailModel;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.RequestAuthorizedModel;
import com.banshuibao.bsb_android.util.ImageUtil;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MediaPlayerUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;
import com.banshuibao.bsb_android.util.TimeUtil;
import com.cunoraz.gifview.library.GifView;

import java.util.List;

/**
 * Created by Administrator on 2017/12/19.
 */

public class PersonalPageAdapter extends MineBaseAdapter<ExpertResultModel.DataBean> {

    private Activity context;

    private String voiceName, voiceContent;
    private MediaPlayer media;
    private String time;
    private MediaPlayerUtil mediaPlayerUtil;
    private int layoutId;

    public PersonalPageAdapter(Activity context, List<ExpertResultModel.DataBean> data, int layoutResId) {
        super(context, data, layoutResId);
        this.context = context;
        this.layoutId = layoutResId;
        mediaPlayerUtil = new MediaPlayerUtil(context);
        mediaPlayerUtil.setOnMediaPlayerPlayingListener(mediaPlayerPlayingListener);
    }

    @Override
    protected void bindData(ViewHolder holder, ExpertResultModel.DataBean item) {
        TextView question = (TextView) holder.getView(R.id.title);
        ImageView head = (ImageView) holder.getView(R.id.header);
        TextView name = (TextView) holder.getView(R.id.name);
        TextView post = (TextView) holder.getView(R.id.skill);
        ImageView tag = (ImageView) holder.getView(R.id.tag);
        TextView date = (TextView) holder.getView(R.id.time);
        TextView buy = (TextView) holder.getView(R.id.buy);
        ImageView more = (ImageView) holder.getView(R.id.more);
        TextView count = (TextView) holder.getView(R.id.count);
        if (item != null) {
            String question_tv = item.getQuestion();
            String headImg = item.getHeadImg();
            String name1 = item.getName();
            String positiotn = item.getPositiotn();
            double quPrice = item.getQuPrice();
            long createDate = item.getCreateDate();
//            LogUtil.e(quPrice);
            if (!TextUtils.isEmpty(question_tv)) {
                question.setText(question_tv);
            }
            if (!TextUtils.isEmpty(name1)) {
                name.setText(name1);
            }
            if (!TextUtils.isEmpty(positiotn)) {
                post.setText(positiotn);
            }
            if (quPrice != 0) {
                buy.setTextColor(context.getResources().getColor(R.color.charge_price));
                buy.setText(quPrice + "元收听");
            } else {
                buy.setTextColor(context.getResources().getColor(R.color.free_price));
                buy.setText("限时免费听");
            }
            if (!TextUtils.isEmpty(headImg)) {
                ImageUtil.loadImageHead(context, headImg, head);
            }
            String time = null;
            if (createDate != 0) {
                time = TimeUtil.format(createDate);
            } else {
                time = "";
            }
            date.setText(time);
        }
        setMediaView(holder.getView(layoutId),item.getExpertVoices(),item);
    }
    private void setMediaView(View view, List<ExpertAnswerDetailModel.DataBean.VoicesBean> datas, ExpertResultModel.DataBean dataBean) {
        final ExpertAnswerDetailModel.DataBean.VoicesBean voicesBean = datas.get(0);
        final VoiceViewHolder holder = new VoiceViewHolder();
        holder.text_tv = view.findViewById(R.id.text_tv);
        holder.show_tv = view.findViewById(R.id.show_tv);
        holder.voice_iv = view.findViewById(R.id.voice_iv);
        holder.voice_gif = view.findViewById(R.id.voice_gif);
        holder.mediaLayout1 = view.findViewById(R.id.media_layout1);
        holder.play = view.findViewById(R.id.play);
        setMediaData(holder, voicesBean, dataBean);
        VoiceViewHolder holder1 = new VoiceViewHolder();
        holder1.text_tv = view.findViewById(R.id.text_tv2);
        holder1.show_tv = view.findViewById(R.id.show_tv2);
        holder1.voice_iv = view.findViewById(R.id.voice_iv2);
        holder1.voice_gif = view.findViewById(R.id.voice_gif2);
        holder1.mediaLayout1 = view.findViewById(R.id.media_layout2);
        holder1.play = view.findViewById(R.id.play2);
        holder1.mediaLayout1.setVisibility(View.VISIBLE);
        holder.show_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        holder.show_tv.getPaint().setAntiAlias(true);//抗锯齿
        holder1.show_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        holder1.show_tv.getPaint().setAntiAlias(true);//抗锯齿
        if (datas.size() > 1) {
            final ExpertAnswerDetailModel.DataBean.VoicesBean voicesBean1 = datas.get(1);
            holder1.mediaLayout1.setVisibility(View.VISIBLE);
            setMediaData(holder1, voicesBean1, dataBean);
        } else
            holder1.mediaLayout1.setVisibility(View.GONE);
    }

    private void setMediaData(final VoiceViewHolder holder, final ExpertAnswerDetailModel.DataBean.VoicesBean voicesBean, final ExpertResultModel.DataBean dataBean) {
        holder.voice_gif.setGifResource(R.raw.play);
        holder.text_tv.setText(TimeUtil.formatDuring(voicesBean.getVoiceTime()));
        holder.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //审请权限
                getAuthorized(dataBean.getUuid(), voicesBean.getUuid(), TimeUtil.formatDuring(voicesBean.getVoiceTime()), holder, "voice", dataBean);
            }
        });
        holder.show_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //审请权限
                getAuthorized(dataBean.getUuid(), voicesBean.getUuid(), TimeUtil.formatDuring(voicesBean.getVoiceTime()), holder, "text", dataBean);
            }
        });
    }

    private Handler handler = new Handler() {
        VoiceViewHolder holder;
        private boolean stop = false;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    if (!stop && holder != null && media != null) {
                        sendEmptyMessageDelayed(0, 1000);
                        holder.text_tv.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
                        holder.play.setEnabled(false);
                        holder.voice_iv.setVisibility(View.GONE);
                        holder.voice_gif.setVisibility(View.VISIBLE);
                    }
                    break;
                case 1:
                    holder = (VoiceViewHolder) msg.obj;
                    stop = false;
                    if (holder != null)
                        holder.play.setEnabled(false);
                    break;
                case 2:
                    if (holder == null || media == null)
                        return;
                    stop = true;
                    holder.voice_iv.setVisibility(View.VISIBLE);
                    holder.voice_gif.setVisibility(View.GONE);
                    holder.play.setEnabled(true);
                    holder.play.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                    holder.text_tv.setText(time);
                    media.pause();
                    media.stop();
                    media.reset();
                    break;
            }
        }
    };

    MediaPlayerUtil.MediaPlayerPlayingListener mediaPlayerPlayingListener = new MediaPlayerUtil.MediaPlayerPlayingListener() {
        @Override
        public void OnError(MediaPlayer mediaPlayer) {

        }

        @Override
        public void OnPrepared(MediaPlayer mediaPlayer) {
            //开始播放
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                handler.sendEmptyMessageDelayed(0, 1000);
            }
        }

        @Override
        public void OnCompletion(MediaPlayer mediaPlayer) {
            stopMedia();
        }
    };

    /**
     * 调用援权接口是否可听可看
     */
    private void getAuthorized(String questionUuid, String voiceUuid, final String during, final VoiceViewHolder holder, final String tag, final ExpertResultModel.DataBean dataBean) {
        if (QuickDoubleClickable.isDoubleClick()) {
            return;
        }
        RequestAuthorizedModel requestAuthorizedModel = new RequestAuthorizedModel();
        requestAuthorizedModel.setUuid(questionUuid);
        requestAuthorizedModel.setVoiceId(voiceUuid);
        HttpUtil.doPost(Constants.Url.AUDIO_AUTHORIZED, requestAuthorizedModel, new HttpResponse(context, AuthorizedResultModel.class) {
            @Override
            public void onResult(Object obj) {
                AuthorizedResultModel resultModel = (AuthorizedResultModel) obj;
                AuthorizedResultModel.DataBean data = resultModel.getData();
                if (data != null) {
                    String type = data.getType();
                    if ("0".equals(type)) {
                        voiceName = data.getVoiceName();
                        voiceContent = data.getVoiceText();
                        if ("voice".equals(tag)) {
                            holder.play.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
                            if (media != null && media.isPlaying()) {
                                media.seekTo(0);
                                stopMedia();
                                holder.play.setEnabled(true);
                                holder.play.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                                holder.voice_gif.setVisibility(View.GONE);
                                holder.voice_iv.setVisibility(View.VISIBLE);
                            } else {
                                time = String.valueOf(during);
                                Message msg = Message.obtain();
                                msg.what = 1;
                                msg.obj = holder;
                                handler.sendMessage(msg);
                                playAudio(voiceName);
                            }
                        } else if ("text".equals(tag)) {
                            showText(voiceContent);
                        }

                    } else if ("1".equals(type)) {
                        voiceName = "";
                        voiceContent = "";
                        showBuy(dataBean);
                    }
                }
            }
        });
    }

    /**
     * 播放语音
     */
    private void playAudio(String name) {
        media = mediaPlayerUtil.getNetMedia(Constants.Url.AUDIO_PLAY + name);
    }

    public void showText(String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
        builder.setMessage(content); //设置内容
        builder.setNegativeButton("已阅", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    /**
     * 是否购买
     */
    private void showBuy(final ExpertResultModel.DataBean dataBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("收听/查看此问题需要支付" + dataBean.getQuPrice() + "元"); //设置内容
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                IntentManager.goPayResultActivity(context, dataBean.getQuestion(), String.valueOf(dataBean.getQuPrice()), dataBean.getUuid(), 5);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }


    public void stopMedia() {
        handler.sendEmptyMessage(2);
    }

    private class VoiceViewHolder {
        LinearLayout mediaLayout1, play;
        TextView text_tv, show_tv;
        ImageView voice_iv;
        GifView voice_gif;
    }

    private class AnswerViewHolder {
        TextView title, name, skill, time, buy, audio_icon, more;
        ImageView header;
    }
}
